#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

#define RTSP_PORT 8554

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    const char* hello = "RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Type: application/sdp\r\nContent-Length: 0\r\n\r\n";

    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        std::cerr << "无法创建套接字" << std::endl;
        return 1;
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(RTSP_PORT);

    // 绑定套接字到地址
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        std::cerr << "绑定失败" << std::endl;
        return 1;
    }

    // 监听套接字
    if (listen(server_fd, 3) < 0) {
        std::cerr << "监听失败" << std::endl;
        return 1;
    }

    // 接受连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
        std::cerr << "接受连接失败" << std::endl;
        return 1;
    }

    // 读取请求
    read(new_socket, buffer, 1024);
    std::cout << "客户端请求：" << std::endl;
    std::cout << buffer << std::endl;

    // 发送响应
    send(new_socket, hello, strlen(hello), 0);
    std::cout << "Hello message sent" << std::endl;

    // 关闭套接字
    close(new_socket);
    close(server_fd);

    return 0;
}
